import { Observable } from 'rxjs';
import { Injectable } from '@angular/core';
import { _HttpClient } from '@delon/theme';
import MD5 from 'md5';

@Injectable({
	providedIn: 'root',
})
export class Cache {
	memoryData = {};

	constructor(private http: _HttpClient) {}

	get(url, params, sortkey?) {
		return this.cache(url, params, this.http.get(url, params));
	}

	post(url, params, sortKey?) {
		return this.cache(url, params, this.http.post(url, params));
	}

	private cache(url, params, req: Observable<any>): Observable<any> {
		const key = this.getKey(url, params);
		return new Observable((x) => {
			if (Object.hasOwn(this.memoryData, key)) {
				x.next(this.memoryData[key]);
			} else {
				req.subscribe((res) => {
					this.memoryData[key] = res;
					x.next(this.memoryData[key]);
				});
			}
		});
	}

	private getKey(url, params) {
		let p_str = [];
		const keys = this.sortKeys(params);
		keys.forEach((i) => {
			if (params[i]) {
				p_str.push(i + '=' + params[i]);
			}
		});

		return MD5(url + '?' + p_str.join('&'));
	}

	private sortKeys(obj) {
		const keys = new Set();
		return Object.keys(obj).sort((a, b) => {
			return a.localeCompare(b);
		});
	}
}
